/**
 * create by gby 20180902
 */
$(function () {
    var obj = new function () {
        'use strict';
        return {
            dataGrid: null,
            param:'',
            form: null,
            List:[],
            photoList: [],
            url:'',
            photoUrl:'',
            clickFlag:false,
            iSchoolId: addressUri.getParam('schoolId'),
            iId: addressUri.getParam('iId'),
            init: function () {
                obj.form = new xhForm($('#xh_form'));
                obj.funObj().fillSelect();
                $('[name="iCustomerId[]"]').select2();
                obj.form.parse();
                obj.listener();
            },
            listener: function () {
                var obj = this;
                $(".form-date").datetimepicker({format: 'yyyy-mm-dd hh:ii:00', language: 'zh-CN', minView: 1, autoclose: true});
                if(info !=null){
                    this.form.fill(info);
                    if(info['iCustomerId[]'] != null){
                        $('[name="iCustomerId[]"]').select2();
                        $('[name="iCustomerId[]"]').val(info['iCustomerId[]'].split(',')).trigger('change');
                    }
                }
                if(visitType != null){
                    obj.funObj().editVisitType();
                }
                if(visitRecord != null){
                    obj.funObj().editVisitRecord();
                }
                //添加访问学校
                $("#bt_sVisitOthers").on('click',function () {
                    obj.funObj().addVisitSchool();
                });
                //添加流程
                $("#bt_sVisitTypeOthers").on('click',function () {
                    obj.funObj().addVisitType();
                });
                //提交
                $('#bt_modal_confirm',parent.document).click(function () {
                    obj.funObj().getParams();
                    obj.funObj().btnSave();
                });
                //附件输出
                if(info){
                    obj.funObj().showFile();
                }
                //日程-删除图片ajax
                $('#fileList').on('click','[id^=imageDelete_]',function () {
                    var deliId=$(this).attr("id").split("_")[1];
                    var rmId=$(this).attr('id').split('_')[2];
                    obj.funObj().fileListImageDel(deliId,rmId);
                });
                //日程-删除附件ajax
                $('#fileList').on('click','[id^=fileDelete_]',function () {
                    var deliId=$(this).attr("id").split("_")[1];
                    var rmId=$(this).attr('id').split('_')[2];
                    obj.funObj().fileListFileDel(deliId,rmId);
                });
                //合影-删除图片ajax
                $('#PhotoList').on('click','[id^=imageDelete_]',function () {
                    var deliId=$(this).attr("id").split("_")[1];
                    var rmId=$(this).attr('id').split('_')[2];
                    obj.funObj().PhotoListImageDel(deliId,rmId);
                });
                //上传日程
                obj.funObj().addESchedule();
                //上传合影
                obj.funObj().addEPhotos();

            },
            funObj: function () {
                var obj = this;
                return {
                    fillSelect: function () {
                        var data = targets['customer'];
                        var str = '<option value="">请选择</option>';
                        $.each(data , function (id,text) {
                            str+='<option value="'+text['id']+'">'+text['name']+'</option>';
                        });
                        $("body").find('[name="iCustomerId[]"]').empty().append(str);
                    },
                    getParams: function () {
                        var params={};
                        for (var i = 0; i < obj.List.length; i++) {
                            obj.url += obj.List[i]['url'] + ',';
                        }
                        for (var i = 0; i < obj.photoList.length; i++) {
                            var footerfixPhoto= obj.photoList[i]['url'].split('.');
                            footerfixPhoto = footerfixPhoto[footerfixPhoto.length-1];
                            footerfixPhoto = footerfixPhoto.toLowerCase()
                            if(footerfixPhoto=='jpg' || footerfixPhoto=='gif' || footerfixPhoto=='png') {  //这里的url只指图片
                                obj.photoUrl += obj.photoList[i]['url'] + ',';
                            }
                        }
                        if(obj.url !=''){
                            params.mESchedule =obj.url;
                        }
                        if(obj.photoUrl != ''){
                            params.mEPhotos = obj.photoUrl;
                        }
                        obj.param = params;
                    },
                    showFileList: function (sImages,sFiles,keyId,divId) {
                        var contentStr = '<table style="width: 100%;"><tr><td>'+timeLine.showImage(sImages,keyId,'',true)+'</td></tr>' +
                            '<tr><td>'+timeLine.showFile(sFiles,keyId,'',true)+'</td></tr>' +
                            '</table>';
                        if (!sImages && !sFiles) {
                            contentStr = '无附件';
                        }
                        $('#'+divId).empty().append(contentStr);
                        $('.images').viewer();
                    },
                    btnSave :function () {
                        obj.form.submit(baseUrl+'school_visit/saveSchoolVisit',obj.param,function (res) {
                            window.top.xhTop.showSuccess(res.msg);
                            try {
                                window.top.xhTop.getActiveFrame()['schoolVisitFrame'].obj.dataGrid.reload();
                            }catch (e) {
                                window.top.xhTop.getActiveFrame().obj.dataGrid.reload();
                            }
                            window.top.xhTop.closeModal();
                        })
                    },
                    addVisitSchool: function () {
                        var visitSchoolTr  = $('.school-box:eq(0)').clone();
                        visitSchoolTr.find('span[class^=select2]').remove();
                        visitSchoolTr.find('[name^=iRId]').remove();
                        $(".school-feildsets").append(visitSchoolTr);
                        visitSchoolTr.find('select').val('').select2();
                        $('[name="iCustomerId[]"]').select2();
                        visitSchoolTr.find('[name^=iPeopleNum]').val('');
                    },
                    addVisitType: function () {
                        var visitTypeTr = $(".type-box:eq(0)").clone(true);
                        visitTypeTr.find('[name^=sContent]').val('');
                        $(".type-feildsets").append(visitTypeTr);
                    },
                    editVisitType:function () {
                        var k = 0;
                        var TypeId= new Array();
                        var sName= new Array();
                        var sContent= new Array();
                        $.each(visitType, function (index, item) {
                            TypeId.push(item.iTId);
                            sName.push(item.sName);
                            sContent.push(item.sContent);
                            k++;
                        });
                        for(var i=0;i < k;i++){
                            var visitTypeTr = $(".type-box:eq(0)").clone(true);

                            if(i==0){
                                $(".type-box:eq(0)")._remove();
                            }
                            visitTypeTr.find('option[value^="'+sName[i]+'"]').attr("selected",true);
                            visitTypeTr.find('textarea[name^="sContent"]').val(sContent[i]);
                            visitTypeTr.find("div:last").append("<input name=\"iTId[]\" type=\"hidden\"  value=\""+ TypeId[i] +"\">");
                            $(".type-feildsets").append(visitTypeTr);
                            obj.form.parse();
                        }
                    },
                    editVisitRecord: function () {
                        var k = 0;
                        var RecordId= new Array();
                        var iCustomerId= new Array();
                        var iPeopleNum= new Array();
                        $.each(visitRecord, function (index, item) {
                            RecordId.push(item.iRId);
                            iCustomerId.push(item.iCustomerId);
                            iPeopleNum.push(item.iPeopleNum);
                             k++;
                        });
                        for(var i=0;i < k;i++){
                            var visitSchoolTr = $('.school-box:eq(0)').clone();
                            visitSchoolTr.find('input[name^=iPeopleNum]').val(iPeopleNum[i]);
                            visitSchoolTr.find('select').before("<input name=\"iRId[]\" type=\"hidden\"  value=\""+ RecordId[i] +"\">");
                            visitSchoolTr.find('span[class^=select2]').remove();
                            visitSchoolTr.find('select').val(iCustomerId[i]).select2();
                            $(".school-feildsets").append(visitSchoolTr);
                            $('[name="iCustomerId[]"]').select2();
                            obj.form.parse();
                        }
                        $('.school-box:eq(0)')._remove();

                    },
                    showFile: function () {
                        var imageESUrl = "";
                        var fileESUrl = "";
                        if(info['mESchedule']){
                            var mESchedule = info['mESchedule'].split(',');
                            for (var i = 0; i < mESchedule.length -1; i++) {
                                var footerESchedule= mESchedule[i].split('.');
                                footerESchedule = footerESchedule[footerESchedule.length-1];
                                footerESchedule = footerESchedule.toLowerCase()
                                if(footerESchedule=='jpg' || footerESchedule=='gif' || footerESchedule=='png') {  //这里的url只指图片
                                    imageESUrl += mESchedule[i] + ',';
                                }else {
                                    fileESUrl+=mESchedule[i]+',';
                                }
                            }
                            obj.funObj().showFileList(imageESUrl,fileESUrl,info['iId'],'fileList');
                        }else {
                            obj.funObj().showFileList('','',info['iId'],'fileList');
                        }
                        obj.funObj().showFileList(info['mEPhotos'],'',info['iId'],'PhotoList');
                    },
                    fileListImageDel: function (deliId,rmId) {
                        myWindow.initPopUp({text: '你确定要删除这张图片吗?'},function () {
                            $.ajax({
                                url:baseUrl+'school_visit/ajaxDelete/fileDelete',
                                data:{'iId':deliId,'rmId':rmId},
                                dataType:'json',
                                type:'post',
                                success:function (data) {
                                    //根据数据更新
                                    location.reload();
                                },
                                error:function (result) {
                                    console.log(result);
                                }
                            });
                        });
                    },
                    fileListFileDel: function (deliId,rmId) {
                        myWindow.initPopUp({text: '你确定要删除这个附件吗?'},function () {
                            $.ajax({
                                url:baseUrl+'school_visit/ajaxDelete/fileDelete',
                                data:{'iId':deliId,'rmId':rmId},
                                dataType:'json',
                                type:'post',
                                success:function (data) {
                                    //根据数据更新
                                    location.reload();
                                },
                                error:function (result) {
                                    console.log(result);
                                }
                            });
                        });
                    },
                    PhotoListImageDel: function (deliId,rmId) {
                        myWindow.initPopUp({text: '你确定要删除这张图片吗?'},function () {
                            $.ajax({
                                url:baseUrl+'school_visit/ajaxDelete',
                                data:{'iId':deliId,'rmId':rmId},
                                dataType:'json',
                                type:'post',
                                success:function (data) {
                                    //根据数据更新
                                    location.reload();
                                },
                                error:function (result) {
                                    console.log(result);
                                }
                            });
                        });
                    },
                    addESchedule: function () {
                        $("#fileInput").fileinput('destroy');
                        fileInput.initFileInput('fileInput',baseUrl+'school_visit/ajaxUpload');
                        var count=0; //记录上传次数
                        $("#fileInput").on("fileuploaded", function (event, data, previewId, index) {
                            count++;
                            obj.List.push({ FileName: data.response.fileName, KeyID: previewId,url:data.response.url });
                            if(obj.clickFlag&&(count==data.files.length)){
                                obj.clickFlag=false;
                                count=0;
                                save();
                            }
                        });
                        $("#fileInput").on("filesuccessremove", function (event, data, previewId, index) {
                            for (var i = 0; i < List.length; i++) {
                                if (List[i].KeyID== data) {
                                    List.splice(i,1);
                                }
                            }
                        });
                    },
                    addEPhotos: function () {
                        $("#photoInput").fileinput('destroy');
                        fileInput.initFileInput('photoInput',baseUrl+'school_visit/ajaxUpload');
                        var count=0; //记录上传次数
                        $("#photoInput").on("fileuploaded", function (event, data, previewId, index) {
                            count++;
                            obj.photoList.push({ FileName: data.response.fileName, KeyID: previewId,url:data.response.url });
                            if(obj.clickFlag&&(count==data.files.length)){
                                obj.clickFlag=false;
                                count=0;
                                save();
                            }
                        });
                        $("#photoInput").on("filesuccessremove", function (event, data, previewId, index) {
                            for (var i = 0; i < obj.List.length; i++) {
                                if (obj.photoList[i].KeyID== data) {
                                    obj.photoList.splice(i,1);
                                }
                            }
                        });
                    }
                }
            }
        }
    };
    obj.init();
});

